package com.dhy.socket;

import com.dhy.socket.handler.DistributeServerInfoHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *     分布式通信服务
 * </p>
 * @author 大忽悠
 * @create 2022/7/5 10:02
 */
@Slf4j
public class DistributedServerSocket {
    private final ServerBootstrap serverBootstrap;
    private final NioEventLoopGroup worker;
    private final DistributeServerInfoHandler serverInfoHandler;
    private Channel channel;

    public DistributedServerSocket() {
        this.serverBootstrap = new ServerBootstrap();
        this.worker = new NioEventLoopGroup();
        this.serverInfoHandler=new DistributeServerInfoHandler();
    }

    /**
     * 启动主实例
     */
    public void start() throws InterruptedException {
        channel=serverBootstrap.group(worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new StringEncoder());
                        //处理读事件
                        ch.pipeline().addLast(serverInfoHandler);
                    }
                })
                .bind(18080).channel();
        log.info("主实例启动完毕!");
        //启动写线程
        serverInfoHandler.channelWrite();
        //关闭回调
        channel.closeFuture().sync();
        log.info("结束运行!");
        close();
    }


    /**
     * 关闭主实例
     */
    public void close(){
        worker.shutdownGracefully();
        serverInfoHandler.close();
        channel.close();
    }
}
